// 全局变量
let currentSection = 'dashboard';
let currentTokensPage = 0;
let currentSmartMoneyPage = 0;
const itemsPerPage = 20;

// API基础URL
const API_BASE = '/api';

// 工具函数
const utils = {
    // 格式化数字
    formatNumber(num, decimals = 2) {
        if (num === null || num === undefined || isNaN(num)) return '-';
        
        if (num >= 1e9) {
            return (num / 1e9).toFixed(decimals) + 'B';
        } else if (num >= 1e6) {
            return (num / 1e6).toFixed(decimals) + 'M';
        } else if (num >= 1e3) {
            return (num / 1e3).toFixed(decimals) + 'K';
        } else {
            return num.toLocaleString(undefined, { 
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals 
            });
        }
    },

    // 格式化百分比
    formatPercentage(num, decimals = 2) {
        if (num === null || num === undefined || isNaN(num)) return '-';
        return num.toFixed(decimals) + '%';
    },

    // 格式化地址
    formatAddress(address, length = 8) {
        if (!address) return '-';
        if (address.length <= length * 2) return address;
        return address.substring(0, length) + '...' + address.substring(address.length - length);
    },

    // 格式化时间
    formatTime(timestamp) {
        if (!timestamp) return '-';
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) return '刚刚';
        if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前';
        if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前';
        if (diff < 604800000) return Math.floor(diff / 86400000) + '天前';
        
        return date.toLocaleDateString('zh-CN');
    },

    // 获取风险等级颜色
    getRiskColor(level) {
        const colors = {
            low: '#22c55e',
            medium: '#f59e0b',
            high: '#ef4444',
            very_high: '#dc2626',
            critical: '#991b1b'
        };
        return colors[level] || '#64748b';
    },

    // 获取变化颜色
    getChangeColor(value) {
        if (value > 0) return '#22c55e';
        if (value < 0) return '#ef4444';
        return '#64748b';
    },

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
};

// API调用函数
const api = {
    async request(endpoint, options = {}) {
        try {
            showLoading();
            const response = await fetch(`${API_BASE}${endpoint}`, {
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers
                },
                ...options
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            hideLoading();
            return data;
        } catch (error) {
            hideLoading();
            console.error('API请求失败:', error);
            showNotification('API请求失败: ' + error.message, 'error');
            throw error;
        }
    },

    // 获取概览数据
    async getSummary() {
        return this.request('/summary');
    },

    // 获取统计数据
    async getStats() {
        return this.request('/stats');
    },

    // 获取代币数据
    async getTokens(params = {}) {
        const queryString = new URLSearchParams(params).toString();
        return this.request(`/tokens?${queryString}`);
    },

    // 获取代币详情
    async getTokenDetail(symbol) {
        return this.request(`/tokens/${symbol}`);
    },

    // 获取聪明钱数据
    async getSmartMoney(params = {}) {
        const queryString = new URLSearchParams(params).toString();
        return this.request(`/smart-money?${queryString}`);
    },

    // 获取聪明钱详情
    async getSmartMoneyDetail(address) {
        return this.request(`/smart-money/${address}`);
    },

    // 获取市场数据
    async getMarketData() {
        return this.request('/market-data');
    },

    // 获取趋势数据
    async getTrends() {
        return this.request('/trends');
    },

    // 获取风险数据
    async getRisks(params = {}) {
        const queryString = new URLSearchParams(params).toString();
        return this.request(`/risks?${queryString}`);
    },

    // 搜索
    async search(query, type = 'all', limit = 20) {
        const params = new URLSearchParams({ q: query, type, limit }).toString();
        return this.request(`/search?${params}`);
    },

    // 刷新数据
    async refreshData() {
        return this.request('/refresh', { method: 'POST' });
    }
};

// UI更新函数
const ui = {
    // 更新概览数据
    updateDashboard(data) {
        if (data.summary) {
            document.getElementById('totalTokens').textContent = data.summary.totalTokens || '-';
            document.getElementById('totalSmartWallets').textContent = data.summary.totalSmartWallets || '-';
            document.getElementById('lastUpdate').textContent = utils.formatTime(data.lastUpdate);
        }

        if (data.summary && data.summary.topTokens) {
            this.renderTopTokens(data.summary.topTokens);
        }

        if (data.summary && data.summary.topSmartWallets) {
            this.renderTopSmartMoney(data.summary.topSmartWallets);
        }
    },

    // 更新统计数据
    updateStats(data) {
        if (data.tokens) {
            document.getElementById('totalTokens').textContent = data.tokens.total || '-';
        }
        if (data.smartMoney) {
            document.getElementById('totalSmartWallets').textContent = data.smartMoney.total || '-';
        }
        if (data.risks) {
            document.getElementById('totalRisks').textContent = data.risks.total || '-';
        }
        
        // 计算总数据点
        const totalDataPoints = (data.tokens?.total || 0) + (data.smartMoney?.total || 0);
        document.getElementById('totalDataPoints').textContent = totalDataPoints;
    },

    // 渲染热门代币
    renderTopTokens(tokens) {
        const container = document.getElementById('topTokensList');
        if (!tokens || tokens.length === 0) {
            container.innerHTML = '<div class="loading">暂无数据</div>';
            return;
        }

        container.innerHTML = tokens.map(token => `
            <div class="token-item card-hover" onclick="showTokenDetail('${token.symbol}')">
                <div class="token-header">
                    <div>
                        <div class="token-symbol">${token.symbol}</div>
                    </div>
                    <div class="token-score">${utils.formatNumber(token.score, 1)}</div>
                </div>
            </div>
        `).join('');
    },

    // 渲染顶级聪明钱
    renderTopSmartMoney(smartMoney) {
        const container = document.getElementById('topSmartMoneyList');
        if (!smartMoney || smartMoney.length === 0) {
            container.innerHTML = '<div class="loading">暂无数据</div>';
            return;
        }

        container.innerHTML = smartMoney.map(wallet => `
            <div class="smart-money-item card-hover" onclick="showSmartMoneyDetail('${wallet.address}')">
                <div class="wallet-header">
                    <div class="wallet-address">${wallet.address}</div>
                    <div class="wallet-score">${utils.formatNumber(wallet.score, 1)}</div>
                </div>
            </div>
        `).join('');
    },

    // 渲染代币列表
    renderTokens(data) {
        const container = document.getElementById('tokensList');
        if (!data.tokens || data.tokens.length === 0) {
            container.innerHTML = '<div class="loading">暂无数据</div>';
            return;
        }

        container.innerHTML = data.tokens.map(token => `
            <div class="token-item card-hover" onclick="showTokenDetail('${token.symbol}')">
                <div class="token-header">
                    <div>
                        <div class="token-symbol">${token.symbol}</div>
                        <div class="token-name">${token.name || '-'}</div>
                    </div>
                    <div class="token-score">${utils.formatNumber(token.score || 0, 1)}</div>
                </div>
                <div class="token-metrics">
                    <div class="metric">
                        <div class="metric-value">$${utils.formatNumber(token.avgPrice || 0, 6)}</div>
                        <div class="metric-label">平均价格</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value" style="color: ${utils.getChangeColor(token.avgPriceChange24h || 0)}">
                            ${utils.formatPercentage(token.avgPriceChange24h || 0)}
                        </div>
                        <div class="metric-label">24h变化</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">$${utils.formatNumber(token.avgVolume24h || 0)}</div>
                        <div class="metric-label">24h交易量</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">$${utils.formatNumber(token.avgMarketCap || 0)}</div>
                        <div class="metric-label">市值</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">${token.sourceCount || 0}</div>
                        <div class="metric-label">数据源</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">${token.category || '-'}</div>
                        <div class="metric-label">分类</div>
                    </div>
                </div>
                ${token.riskFactors && token.riskFactors.length > 0 ? `
                    <div class="wallet-tags">
                        ${token.riskFactors.map(risk => `<span class="tag">${risk}</span>`).join('')}
                    </div>
                ` : ''}
            </div>
        `).join('');

        // 更新分页
        this.renderPagination('tokensPagination', data.pagination, (page) => {
            currentTokensPage = page;
            loadTokens();
        });
    },

    // 渲染聪明钱列表
    renderSmartMoney(data) {
        const container = document.getElementById('smartMoneyList');
        if (!data.smartMoney || data.smartMoney.length === 0) {
            container.innerHTML = '<div class="loading">暂无数据</div>';
            return;
        }

        container.innerHTML = data.smartMoney.map(wallet => `
            <div class="smart-money-item card-hover" onclick="showSmartMoneyDetail('${wallet.address}')">
                <div class="wallet-header">
                    <div>
                        <div class="wallet-address">${utils.formatAddress(wallet.address)}</div>
                        ${wallet.nickname ? `<div class="token-name">${wallet.nickname}</div>` : ''}
                    </div>
                    <div class="wallet-score">${utils.formatNumber(wallet.smartScore || 0, 1)}</div>
                </div>
                ${wallet.tags && wallet.tags.length > 0 ? `
                    <div class="wallet-tags">
                        ${wallet.tags.map(tag => `<span class="tag ${tag}">${tag}</span>`).join('')}
                    </div>
                ` : ''}
                <div class="token-metrics">
                    <div class="metric">
                        <div class="metric-value" style="color: ${utils.getChangeColor(wallet.avgPnl7d || 0)}">
                            $${utils.formatNumber(wallet.avgPnl7d || 0)}
                        </div>
                        <div class="metric-label">7天PnL</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value" style="color: ${utils.getChangeColor(wallet.avgPnl30d || 0)}">
                            $${utils.formatNumber(wallet.avgPnl30d || 0)}
                        </div>
                        <div class="metric-label">30天PnL</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">${utils.formatPercentage((wallet.metrics?.winRate || 0) * 100)}</div>
                        <div class="metric-label">胜率</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">${wallet.metrics?.totalTrades || 0}</div>
                        <div class="metric-label">总交易数</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">$${utils.formatNumber(wallet.metrics?.totalVolume || 0)}</div>
                        <div class="metric-label">总交易量</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value" style="color: ${utils.getRiskColor(wallet.riskLevel)}">
                            ${wallet.riskLevel || '-'}
                        </div>
                        <div class="metric-label">风险等级</div>
                    </div>
                </div>
            </div>
        `).join('');

        // 更新分页
        this.renderPagination('smartMoneyPagination', data.pagination, (page) => {
            currentSmartMoneyPage = page;
            loadSmartMoney();
        });
    },

    // 渲染市场数据
    renderMarketData(data) {
        const container = document.getElementById('marketData');
        
        if (!data.overview) {
            container.innerHTML = '<div class="loading">暂无市场数据</div>';
            return;
        }

        const overview = data.overview;
        container.innerHTML = `
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">💰</div>
                    <div class="stat-content">
                        <div class="stat-value">$${utils.formatNumber(overview.totalMarketCap?.usd || 0)}</div>
                        <div class="stat-label">总市值</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📊</div>
                    <div class="stat-content">
                        <div class="stat-value">$${utils.formatNumber(overview.totalVolume?.usd || 0)}</div>
                        <div class="stat-label">24h交易量</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📈</div>
                    <div class="stat-content">
                        <div class="stat-value" style="color: ${utils.getChangeColor(overview.marketCapChange24h || 0)}">
                            ${utils.formatPercentage(overview.marketCapChange24h || 0)}
                        </div>
                        <div class="stat-label">24h市值变化</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">🪙</div>
                    <div class="stat-content">
                        <div class="stat-value">${utils.formatNumber(overview.activeCryptocurrencies || 0, 0)}</div>
                        <div class="stat-label">活跃加密货币</div>
                    </div>
                </div>
            </div>
        `;
    },

    // 渲染趋势数据
    renderTrends(data) {
        const container = document.getElementById('trendsData');
        
        if (!data.price && !data.volume) {
            container.innerHTML = '<div class="loading">暂无趋势数据</div>';
            return;
        }

        container.innerHTML = `
            <div class="trends-grid">
                ${data.price ? `
                    <div class="trend-item">
                        <h4>价格趋势</h4>
                        <div class="trend-indicator ${data.price.direction}">
                            <span class="trend-direction">${this.getTrendIcon(data.price.direction)}</span>
                            <span class="trend-strength">${data.price.strength}</span>
                        </div>
                        ${data.price.change ? `
                            <div class="trend-change" style="color: ${utils.getChangeColor(data.price.change)}">
                                ${utils.formatPercentage(data.price.change * 100)}
                            </div>
                        ` : ''}
                    </div>
                ` : ''}
                ${data.volume ? `
                    <div class="trend-item">
                        <h4>交易量趋势</h4>
                        <div class="trend-indicator ${data.volume.direction}">
                            <span class="trend-direction">${this.getTrendIcon(data.volume.direction)}</span>
                            <span class="trend-strength">${data.volume.strength}</span>
                        </div>
                        ${data.volume.change ? `
                            <div class="trend-change" style="color: ${utils.getChangeColor(data.volume.change)}">
                                ${utils.formatPercentage(data.volume.change * 100)}
                            </div>
                        ` : ''}
                    </div>
                ` : ''}
                ${data.social ? `
                    <div class="trend-item">
                        <h4>社交媒体</h4>
                        <div class="social-metrics">
                            <div class="metric">
                                <span class="metric-value">${data.social.totalMentions || 0}</span>
                                <span class="metric-label">总提及数</span>
                            </div>
                            <div class="metric">
                                <span class="metric-value">${data.social.sentiment || 'neutral'}</span>
                                <span class="metric-label">情感倾向</span>
                            </div>
                        </div>
                    </div>
                ` : ''}
            </div>
        `;
    },

    // 渲染风险列表
    renderRisks(data) {
        const container = document.getElementById('risksList');
        if (!data.risks || data.risks.length === 0) {
            container.innerHTML = '<div class="loading">暂无风险数据</div>';
            return;
        }

        container.innerHTML = data.risks.map(risk => `
            <div class="risk-item ${risk.severity}">
                <div class="risk-header">
                    <div class="risk-type">${risk.type}</div>
                    <div class="risk-severity ${risk.severity}">${risk.severity}</div>
                </div>
                <div class="risk-description">${risk.description}</div>
                ${risk.token ? `<div class="risk-token">相关代币: ${risk.token}</div>` : ''}
            </div>
        `).join('');
    },

    // 渲染分页
    renderPagination(containerId, pagination, onPageChange) {
        const container = document.getElementById(containerId);
        if (!pagination || pagination.total === 0) {
            container.innerHTML = '';
            return;
        }

        const currentPage = Math.floor(pagination.offset / pagination.limit);
        const totalPages = Math.ceil(pagination.total / pagination.limit);
        
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <button class="pagination-btn" ${currentPage === 0 ? 'disabled' : ''} 
                    onclick="changePage(${currentPage - 1})">
                ← 上一页
            </button>
        `;
        
        // 页码按钮
        const startPage = Math.max(0, currentPage - 2);
        const endPage = Math.min(totalPages - 1, currentPage + 2);
        
        for (let i = startPage; i <= endPage; i++) {
            paginationHTML += `
                <button class="pagination-btn ${i === currentPage ? 'active' : ''}" 
                        onclick="changePage(${i})">
                    ${i + 1}
                </button>
            `;
        }
        
        // 下一页按钮
        paginationHTML += `
            <button class="pagination-btn" ${currentPage >= totalPages - 1 ? 'disabled' : ''} 
                    onclick="changePage(${currentPage + 1})">
                下一页 →
            </button>
        `;
        
        container.innerHTML = paginationHTML;
        
        // 保存回调函数
        window.changePage = onPageChange;
    },

    // 获取趋势图标
    getTrendIcon(direction) {
        const icons = {
            up: '📈',
            down: '📉',
            neutral: '➡️'
        };
        return icons[direction] || '➡️';
    }
};

// 数据加载函数
async function loadDashboard() {
    try {
        const [summaryData, statsData] = await Promise.all([
            api.getSummary(),
            api.getStats()
        ]);
        
        if (summaryData.success) {
            ui.updateDashboard(summaryData.data);
        }
        
        if (statsData.success) {
            ui.updateStats(statsData.data);
        }
    } catch (error) {
        console.error('加载概览数据失败:', error);
    }
}

async function loadTokens() {
    try {
        const params = {
            limit: itemsPerPage,
            offset: currentTokensPage * itemsPerPage,
            sortBy: document.getElementById('tokenSort')?.value || 'score',
            order: 'desc'
        };
        
        const category = document.getElementById('tokenCategory')?.value;
        if (category) params.category = category;
        
        const data = await api.getTokens(params);
        if (data.success) {
            ui.renderTokens(data.data);
        }
    } catch (error) {
        console.error('加载代币数据失败:', error);
    }
}

async function loadSmartMoney() {
    try {
        const params = {
            limit: itemsPerPage,
            offset: currentSmartMoneyPage * itemsPerPage,
            sortBy: document.getElementById('smartMoneySort')?.value || 'smartScore',
            order: 'desc'
        };
        
        const riskLevel = document.getElementById('smartMoneyRisk')?.value;
        if (riskLevel) params.riskLevel = riskLevel;
        
        const data = await api.getSmartMoney(params);
        if (data.success) {
            ui.renderSmartMoney(data.data);
        }
    } catch (error) {
        console.error('加载聪明钱数据失败:', error);
    }
}

async function loadMarketData() {
    try {
        const [marketData, trendsData] = await Promise.all([
            api.getMarketData(),
            api.getTrends()
        ]);
        
        if (marketData.success) {
            ui.renderMarketData(marketData.data);
        }
        
        if (trendsData.success) {
            ui.renderTrends(trendsData.data);
        }
    } catch (error) {
        console.error('加载市场数据失败:', error);
    }
}

async function loadRisks() {
    try {
        const params = {};
        const severity = document.getElementById('riskSeverity')?.value;
        if (severity) params.severity = severity;
        
        const data = await api.getRisks(params);
        if (data.success) {
            ui.renderRisks(data.data);
        }
    } catch (error) {
        console.error('加载风险数据失败:', error);
    }
}

// 详情显示函数
async function showTokenDetail(symbol) {
    try {
        const data = await api.getTokenDetail(symbol);
        if (data.success) {
            const token = data.data;
            const modalBody = document.getElementById('modalBody');
            modalBody.innerHTML = `
                <h3>${token.symbol} - ${token.name || '未知'}</h3>
                <div class="detail-grid">
                    <div class="detail-item">
                        <label>综合评分:</label>
                        <span>${utils.formatNumber(token.score || 0, 1)}</span>
                    </div>
                    <div class="detail-item">
                        <label>平均价格:</label>
                        <span>$${utils.formatNumber(token.avgPrice || 0, 6)}</span>
                    </div>
                    <div class="detail-item">
                        <label>24h价格变化:</label>
                        <span style="color: ${utils.getChangeColor(token.avgPriceChange24h || 0)}">
                            ${utils.formatPercentage(token.avgPriceChange24h || 0)}
                        </span>
                    </div>
                    <div class="detail-item">
                        <label>24h交易量:</label>
                        <span>$${utils.formatNumber(token.avgVolume24h || 0)}</span>
                    </div>
                    <div class="detail-item">
                        <label>市值:</label>
                        <span>$${utils.formatNumber(token.avgMarketCap || 0)}</span>
                    </div>
                    <div class="detail-item">
                        <label>数据源数量:</label>
                        <span>${token.sourceCount || 0}</span>
                    </div>
                    <div class="detail-item">
                        <label>分类:</label>
                        <span>${token.category || '-'}</span>
                    </div>
                    ${token.riskFactors && token.riskFactors.length > 0 ? `
                        <div class="detail-item">
                            <label>风险因素:</label>
                            <div class="wallet-tags">
                                ${token.riskFactors.map(risk => `<span class="tag">${risk}</span>`).join('')}
                            </div>
                        </div>
                    ` : ''}
                </div>
            `;
            showModal();
        }
    } catch (error) {
        console.error('获取代币详情失败:', error);
    }
}

async function showSmartMoneyDetail(address) {
    try {
        const data = await api.getSmartMoneyDetail(address);
        if (data.success) {
            const wallet = data.data;
            const modalBody = document.getElementById('modalBody');
            modalBody.innerHTML = `
                <h3>聪明钱钱包详情</h3>
                <div class="detail-grid">
                    <div class="detail-item">
                        <label>钱包地址:</label>
                        <span class="wallet-address">${wallet.address}</span>
                    </div>
                    ${wallet.nickname ? `
                        <div class="detail-item">
                            <label>昵称:</label>
                            <span>${wallet.nickname}</span>
                        </div>
                    ` : ''}
                    <div class="detail-item">
                        <label>智能评分:</label>
                        <span>${utils.formatNumber(wallet.smartScore || 0, 1)}</span>
                    </div>
                    <div class="detail-item">
                        <label>7天PnL:</label>
                        <span style="color: ${utils.getChangeColor(wallet.avgPnl7d || 0)}">
                            $${utils.formatNumber(wallet.avgPnl7d || 0)}
                        </span>
                    </div>
                    <div class="detail-item">
                        <label>30天PnL:</label>
                        <span style="color: ${utils.getChangeColor(wallet.avgPnl30d || 0)}">
                            $${utils.formatNumber(wallet.avgPnl30d || 0)}
                        </span>
                    </div>
                    <div class="detail-item">
                        <label>胜率:</label>
                        <span>${utils.formatPercentage((wallet.metrics?.winRate || 0) * 100)}</span>
                    </div>
                    <div class="detail-item">
                        <label>总交易数:</label>
                        <span>${wallet.metrics?.totalTrades || 0}</span>
                    </div>
                    <div class="detail-item">
                        <label>平均持有时间:</label>
                        <span>${utils.formatNumber(wallet.metrics?.avgHoldTime || 0, 1)} 天</span>
                    </div>
                    <div class="detail-item">
                        <label>总交易量:</label>
                        <span>$${utils.formatNumber(wallet.metrics?.totalVolume || 0)}</span>
                    </div>
                    <div class="detail-item">
                        <label>风险等级:</label>
                        <span style="color: ${utils.getRiskColor(wallet.riskLevel)}">
                            ${wallet.riskLevel || '-'}
                        </span>
                    </div>
                    ${wallet.tags && wallet.tags.length > 0 ? `
                        <div class="detail-item">
                            <label>标签:</label>
                            <div class="wallet-tags">
                                ${wallet.tags.map(tag => `<span class="tag ${tag}">${tag}</span>`).join('')}
                            </div>
                        </div>
                    ` : ''}
                </div>
            `;
            showModal();
        }
    } catch (error) {
        console.error('获取聪明钱详情失败:', error);
    }
}

// 搜索功能
const searchHandler = utils.debounce(async () => {
    const query = document.getElementById('searchInput').value.trim();
    const type = document.getElementById('searchType').value;
    
    if (query.length < 2) {
        showNotification('搜索关键词至少需要2个字符', 'warning');
        return;
    }
    
    try {
        const data = await api.search(query, type);
        if (data.success) {
            showSearchResults(data.data, query);
        }
    } catch (error) {
        console.error('搜索失败:', error);
    }
}, 500);

function showSearchResults(results, query) {
    const modalBody = document.getElementById('modalBody');
    modalBody.innerHTML = `
        <h3>搜索结果: "${query}"</h3>
        <div class="search-results">
            ${results.tokens && results.tokens.length > 0 ? `
                <div class="search-section">
                    <h4>代币 (${results.tokens.length})</h4>
                    <div class="search-items">
                        ${results.tokens.map(token => `
                            <div class="search-item" onclick="showTokenDetail('${token.symbol}')">
                                <div class="search-item-title">${token.symbol} - ${token.name || '未知'}</div>
                                <div class="search-item-meta">评分: ${utils.formatNumber(token.score || 0, 1)}</div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            ` : ''}
            ${results.smartMoney && results.smartMoney.length > 0 ? `
                <div class="search-section">
                    <h4>聪明钱 (${results.smartMoney.length})</h4>
                    <div class="search-items">
                        ${results.smartMoney.map(wallet => `
                            <div class="search-item" onclick="showSmartMoneyDetail('${wallet.address}')">
                                <div class="search-item-title">${utils.formatAddress(wallet.address)}</div>
                                <div class="search-item-meta">
                                    评分: ${utils.formatNumber(wallet.smartScore || 0, 1)}
                                    ${wallet.nickname ? ` | ${wallet.nickname}` : ''}
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            ` : ''}
            ${results.total === 0 ? '<div class="no-results">未找到相关结果</div>' : ''}
        </div>
    `;
    showModal();
}

// 刷新数据
async function refreshData() {
    try {
        const refreshBtn = document.getElementById('refreshBtn');
        refreshBtn.disabled = true;
        refreshBtn.innerHTML = '<span class="refresh-icon pulse">🔄</span> 刷新中...';
        
        const data = await api.refreshData();
        if (data.success) {
            showNotification('数据刷新已启动', 'success');
            // 重新加载当前页面数据
            setTimeout(() => {
                loadCurrentSection();
            }, 2000);
        }
    } catch (error) {
        console.error('刷新数据失败:', error);
    } finally {
        const refreshBtn = document.getElementById('refreshBtn');
        refreshBtn.disabled = false;
        refreshBtn.innerHTML = '<span class="refresh-icon">🔄</span> 刷新数据';
    }
}

// 导航功能
function switchSection(sectionId) {
    // 隐藏所有内容区域
    document.querySelectorAll('.content-section').forEach(section => {
        section.classList.remove('active');
    });
    
    // 显示目标区域
    document.getElementById(sectionId).classList.add('active');
    
    // 更新导航状态
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.remove('active');
    });
    document.querySelector(`[data-section="${sectionId}"]`).classList.add('active');
    
    currentSection = sectionId;
    loadCurrentSection();
}

function loadCurrentSection() {
    switch (currentSection) {
        case 'dashboard':
            loadDashboard();
            break;
        case 'tokens':
            loadTokens();
            break;
        case 'smart-money':
            loadSmartMoney();
            break;
        case 'market':
            loadMarketData();
            break;
        case 'risks':
            loadRisks();
            break;
    }
}

// 模态框功能
function showModal() {
    document.getElementById('modal').style.display = 'block';
}

function hideModal() {
    document.getElementById('modal').style.display = 'none';
}

// 加载指示器
function showLoading() {
    document.getElementById('loadingIndicator').classList.add('show');
}

function hideLoading() {
    document.getElementById('loadingIndicator').classList.remove('show');
}

// 通知功能
function showNotification(message, type = 'info') {
    const notification = document.getElementById('notification');
    const notificationText = document.getElementById('notificationText');
    
    notificationText.textContent = message;
    notification.className = `notification ${type}`;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 5000);
}

// 事件监听器
document.addEventListener('DOMContentLoaded', () => {
    // 导航点击事件
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const sectionId = link.getAttribute('data-section');
            switchSection(sectionId);
        });
    });
    
    // 移动端导航切换
    const navToggle = document.getElementById('navToggle');
    const navMenu = document.getElementById('navMenu');
    
    navToggle.addEventListener('click', () => {
        navToggle.classList.toggle('active');
        navMenu.classList.toggle('active');
    });
    
    // 搜索事件
    document.getElementById('searchBtn').addEventListener('click', searchHandler);
    document.getElementById('searchInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            searchHandler();
        }
    });
    
    // 刷新按钮事件
    document.getElementById('refreshBtn').addEventListener('click', refreshData);
    
    // 过滤器变化事件
    document.getElementById('tokenCategory')?.addEventListener('change', () => {
        currentTokensPage = 0;
        loadTokens();
    });
    
    document.getElementById('tokenSort')?.addEventListener('change', () => {
        currentTokensPage = 0;
        loadTokens();
    });
    
    document.getElementById('smartMoneyRisk')?.addEventListener('change', () => {
        currentSmartMoneyPage = 0;
        loadSmartMoney();
    });
    
    document.getElementById('smartMoneySort')?.addEventListener('change', () => {
        currentSmartMoneyPage = 0;
        loadSmartMoney();
    });
    
    document.getElementById('riskSeverity')?.addEventListener('change', loadRisks);
    
    // 模态框关闭事件
    document.querySelector('.modal-close').addEventListener('click', hideModal);
    document.getElementById('modal').addEventListener('click', (e) => {
        if (e.target === document.getElementById('modal')) {
            hideModal();
        }
    });
    
    // 通知关闭事件
    document.getElementById('notificationClose').addEventListener('click', () => {
        document.getElementById('notification').classList.remove('show');
    });
    
    // 键盘事件
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            hideModal();
        }
    });
    
    // 初始加载
    loadDashboard();
});

// 全局函数暴露
window.showTokenDetail = showTokenDetail;
window.showSmartMoneyDetail = showSmartMoneyDetail;
window.refreshData = refreshData;

